#include "./atol.h"
#define STATE_NOT_MATCH 0
#define STATE_MATCHING_NAGETIVE_NUM -1
#define STATE_MATCHING_POSITIVE_NUM 1
#define STATE_NAGETIVE_OUT_OF_RANGE -10
#define STATE_POSITIVE_OUT_OF_RANGE 10
#define MAX_NUM LONG_MAX
#define MIN_NUM LONG_MIN
extern long gim_atol(char *buf, size_t len)
{
  long num = 0;
  char state = STATE_NOT_MATCH;
  for (size_t i = 0; i < len; i++)
  {
    char l = buf[i];
    if (state == STATE_NOT_MATCH)
    {
      if (l == '-')
      {
        state = STATE_MATCHING_NAGETIVE_NUM;
        continue;
      }
      if (l == '+' || l >= '0' && l <= '9')
      {
        state = STATE_MATCHING_POSITIVE_NUM;
      }
      else
      {
        continue;
      }
    }
    if (l < '0' || l > '9')
      break;

    if (num > MAX_NUM / 10)
    {
      state *= 10;
      break;
    }
    num = 10 * num + l - '0';
  }

  if (state == STATE_POSITIVE_OUT_OF_RANGE)
    return MAX_NUM;
  else if (state == STATE_NAGETIVE_OUT_OF_RANGE)
    return MIN_NUM;
  else
    return state * num;
}
